package com.college.eduService.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.college.eduService.client.CommentClient;
import com.college.eduService.entity.EduCourseDescription;
import com.college.eduService.entity.EduTeacher;
import com.college.eduService.entity.frontvo.CourseFrontVo;
import com.college.eduService.entity.frontvo.CourseWebVo;
import com.college.eduService.entity.vo.CourseInfoVo;
import com.college.eduService.entity.vo.CoursePublishVo;
import com.college.eduService.entity.query.CourseQuery;
import com.college.eduService.service.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.*;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.college.eduService.mapper.EduCourseMapper;
import com.college.eduService.entity.EduCourse;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

@Service
public class EduCourseServiceImpl extends ServiceImpl<EduCourseMapper, EduCourse> implements EduCourseService{
    @Autowired
    EduCourseDescriptionService descriptionService;
    @Autowired
    EduVideoService videoService;
    @Autowired
    EduChapterService chapterService;
    @Autowired
    EduTeacherService teacherService;
    @Autowired
    private CommentClient commentClient;

    //播放历史课程集合
    private List<EduCourse> list=new ArrayList<>();

    //添加课程
    @Override
    @Transactional
    public String saveCourse(CourseInfoVo courseInfoVo) {
            //向课程表、描述表中添加数据
            EduCourse course=new EduCourse();
            BeanUtils.copyProperties(courseInfoVo,course);
            //生成随机主键
            String val="1";
            Random random = new Random();
            for (int i = 0; i < 18; i++) {
                val+=String.valueOf(random.nextInt(10));
            }
            course.setId(val);
            boolean savecourse = this.save(course);
            if(savecourse){
            //向课程简介表添加数据
            EduCourseDescription description=new EduCourseDescription();
            BeanUtils.copyProperties(courseInfoVo,description);
            description.setId(val);
            descriptionService.save(description);
        }

            return  val;
    }
    //根据id查询
    @Override
    public CourseInfoVo getCourseById(String courseId) {
        //课程表
        EduCourse eduCourse=baseMapper.selectById(courseId);
        CourseInfoVo courseInfoVo=new CourseInfoVo();
        BeanUtils.copyProperties(eduCourse,courseInfoVo);
        //描述表
        EduCourseDescription courseDescription=descriptionService.getById(courseInfoVo.getId());
        courseInfoVo.setDescription(courseDescription.getDescription());
        return courseInfoVo;
    }
    //修改课程表和描述表的信息
    @Override
    public void UpdateCourse(CourseInfoVo courseInfoVo) {
        EduCourse eduCourse=new EduCourse();
        BeanUtils.copyProperties(courseInfoVo,eduCourse);
        int update=baseMapper.updateById(eduCourse);
        if(update>0){
            EduCourseDescription description=new EduCourseDescription();
            BeanUtils.copyProperties(courseInfoVo,description);
            descriptionService.updateById(description);
        }
    }
    //根据id显示最终提交信息
    @Override
    public CoursePublishVo publishCourseInfo(String id) {
        CoursePublishVo publishVo=baseMapper.getCoursePublishVo(id);
        return publishVo;
    }
    //分页查询
    @Override
    public Page<EduCourse> pageQuery(Integer current, Integer limit, CourseQuery courseQuery) {
        Page <EduCourse> page = new Page <>(current,limit);
        QueryWrapper<EduCourse> wrapper = new QueryWrapper <>();
        String title = courseQuery.getTitle();
        String subjectId = courseQuery.getSubjectId();
        String subjectParentId = courseQuery.getSubjectParentId();
        String teacherId = courseQuery.getTeacherId();
        String status=courseQuery.getStatus();
        //判空,构造查询条件
        if(StringUtils.hasText(title)){
            wrapper.like("title",title);
        }
        if(StringUtils.hasText(subjectId)){
            wrapper.eq("subject_id",subjectId);
        }
        if(StringUtils.hasText(subjectParentId)){
            wrapper.eq("subject_parent_id",subjectParentId);
        }
        if(StringUtils.hasText(teacherId)){
            wrapper.eq("teacher_id",teacherId);
        }
        if(StringUtils.hasText(status)){
            wrapper.eq("status",status);
        }else{
            wrapper.eq("status","Normal");
        }
        wrapper.orderByDesc("gmt_create");
        //进行分页查询
        this.baseMapper.selectPage(page, wrapper);//分页查询后自动封装到page中
        return page;
    }
    //删除课程
    @Override
    public void removeCourse(String id) {
        //1.删除小节
        videoService.removeVideoByCourseId(id);
        //2.删除章节
        chapterService.removeChapterByCourseId(id);
        //3.删除课程描述信息
        descriptionService.removeById(id);
        //4.删除课程信息
        this.baseMapper.deleteById(id);
    }
    //查询8个热门课程
    @Override
    public List<EduCourse> selectHotCourse() {

        //查询前8条热门课程
        QueryWrapper<EduCourse> wrapper = new QueryWrapper<>();
        wrapper.orderByDesc("view_count");
        wrapper.last("limit 8");
        wrapper.eq("status","Normal");
        List<EduCourse> eduCourses = baseMapper.selectList(wrapper);
        eduCourses.forEach(course->
                course.setCommentNum(commentClient.getCommentCount(course.getId()))
                );
        return eduCourses;

    }

    //前台多条件查询
    @Override
    public Map<String, Object> getCourseFrontInfo(Page<EduCourse> pageCourse, CourseFrontVo courseFrontVo) {
        String title = null;
        String subjectId = null;
        String subjectParentId = null;
        String gmtCreateSort = null;
        String buyCountSort = null;
        String priceSort = null;
        String teacherId = null;

        if (!StringUtils.isEmpty(courseFrontVo)){
            title = courseFrontVo.getTitle();
            subjectId = courseFrontVo.getSubjectId();
            subjectParentId = courseFrontVo.getSubjectParentId();
            gmtCreateSort = courseFrontVo.getGmtCreateSort();
            buyCountSort = courseFrontVo.getBuyCountSort();
            priceSort = courseFrontVo.getPriceSort();
            teacherId = courseFrontVo.getTeacherId();
        }


        QueryWrapper<EduCourse> wrapper = new QueryWrapper<>();
        //判断条件值是否为空，不为空拼接条件
        if (!StringUtils.isEmpty(title)){
            wrapper.like("title",title);
        }
        if (!StringUtils.isEmpty(subjectParentId)){//一级分类
            wrapper.eq("subject_parent_id",subjectParentId);
        }
        if (!StringUtils.isEmpty(subjectId)){//二级分类
            wrapper.eq("subject_id",subjectId);
        }
        if (!StringUtils.isEmpty(buyCountSort)){//关注度
            wrapper.orderByDesc("buy_count");
        }
        if (!StringUtils.isEmpty(priceSort)){//价格
            wrapper.orderByDesc("price");
        }
        if (!StringUtils.isEmpty(gmtCreateSort)){//最新，创建时间
            wrapper.orderByDesc("gmt_create");
        }
            wrapper.eq("status","Normal");

        baseMapper.selectPage(pageCourse, wrapper);

        long total = pageCourse.getTotal();//总记录数
        List<EduCourse> courseList = pageCourse.getRecords();//数据集合
        courseList.forEach(course->
                course.setCommentNum(commentClient.getCommentCount(course.getId()))
        );
        long size = pageCourse.getSize();//每页记录数
        long current = pageCourse.getCurrent();//当前页
        long pages = pageCourse.getPages();//总页数
        boolean hasPrevious = pageCourse.hasPrevious();//是否有上一页
        boolean hasNext = pageCourse.hasNext();//是否有下一页

        HashMap<String, Object> map = new HashMap<>();
        map.put("total",total);
        map.put("list",courseList);
        map.put("size",size);
        map.put("current",current);
        map.put("pages",pages);
        map.put("hasPrevious",hasPrevious);
        map.put("hasNext",hasNext);

        return map;
    }

    //前台课程详情
    @Override
    public CourseWebVo getBaseCourseInfo(String courseId) {
        return baseMapper.getBaseCourseInfo(courseId);
    }
    //播放历史课程集合
    @Override
    public List<EduCourse> getCourseHistory(String courseId) {
        EduCourse course=baseMapper.selectById(courseId);
        //如果集合中没有数据则添加一条数据
        if(list.size()>0) {
            for (int i = 0; i < list.size(); i++) {
                System.out.println(list.get(i).getId().equals(course.getId()));
                //判断集合中是否有此条课程信息
                if (list.get(i).getId().equals(course.getId())) {
                    //如果有则更新播放时间
                    list.get(i).setPlayDate(new Date());
                    return list;
                }
            }
            //添加数据
            course.setPlayDate(new Date());
            list.add(course);
        }else{
            //添加数据
            course.setPlayDate(new Date());
            list.add(course);
        }
        return list;
    }
}
